library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity ps2_kb_scode_rx is
  port (
    reset    : in std_logic;
    clock    : in std_logic;

    dev_dat  : in std_logic;

    clear    : in std_logic;
    rd_bit   : in std_logic;

    scode    : out std_logic_vector (7 downto 0);
    error    : out std_logic;

    scode_rd : out std_logic
  );
end entity ps2_kb_scode_rx;

architecture default of ps2_kb_scode_rx is
  signal data_reg : std_logic_vector (8 downto 0);
  signal bits_ctr : unsigned (3 downto 0);
begin
  process (reset, clock) is
  begin
    if reset = '1' then
      data_reg <= (data_reg'range => '0');
      bits_ctr <= (bits_ctr'range => '0');
    elsif rising_edge (clock) then
      scode_rd <= '0';
      if clear = '1' then
        data_reg <= (data_reg'range => '0');
        bits_ctr <= (bits_ctr'range => '0');
      elsif rd_bit = '1' then
        data_reg <= dev_dat & data_reg (8 downto 1);
        bits_ctr <= bits_ctr + 1;
        if bits_ctr = "1000" then
          scode_rd <= '1';
          bits_ctr <= (bits_ctr'range => '0');
        end if;
      end if;
    end if;
  end process;

  process (data_reg) is
    variable temp : std_logic;
  begin
    temp := '1';
    for i in data_reg'range loop
      temp := temp xor data_reg (i);
    end loop;
    error <= temp;
  end process;

  scode <= data_reg (7 downto 0);
end architecture default;
